package com.qingke.oms.command.shop;

import java.util.ArrayList;
import java.util.List;

import com.qingke.oms.dao.OrderManagementSystemDAO;
import com.qingke.oms.pojo.GoodsStatistic;
import com.qingke.oms.pojo.ShelfRecord;
import com.qingke.oms.pojo.ShelfStatus;
import com.qingke.oms.pojo.ShipmentRecord;
import com.qingke.oms.pojo.ShipmentStatus;
import com.qingke.oms.util.OMSConsole;

public interface UpdateGoodsStatistic {
	default void updateGoodsStatistic(){
		OrderManagementSystemDAO dao=new OrderManagementSystemDAO();
		ShelfStatus onShelfStatus=dao.selectShelfStatusByStatus("on shelf");
		ShelfStatus offShelfStatus=dao.selectShelfStatusByStatus("off shelf");
		ShipmentStatus notShipmentShelfStatus=dao.selectShipmentStatusByStatus("not shipped");
		
		List<ShelfRecord> onGoodsRecord=dao.selectShelfRecordByShelfStatus(onShelfStatus);
		List<ShelfRecord> offGoodsRecord=dao.selectShelfRecordByShelfStatus(offShelfStatus);
		List<ShipmentRecord> shipmentGoodsRecord=dao.selectShipmentRecordByShipmentStatus(notShipmentShelfStatus);
		
		List<GoodsStatistic> newest=new ArrayList<>();
		for(ShelfRecord on:onGoodsRecord){
			boolean isExist=false;
			GoodsStatistic gr=null;
			for(GoodsStatistic gs:newest){
				if(gs.getShop().getId()==on.getShop().getId()&&gs.getGoods().getId()==on.getGoods().getId()){
					isExist=true;
					gr=gs;
					break;
				}
			}
			if(!isExist){
				gr=new GoodsStatistic();
				gr.setShop(on.getShop());
				gr.setGoods(on.getGoods());
				newest.add(gr);
			}
			gr.setStock(gr.getStock()+on.getQuantity());
			
		}
		
		for(GoodsStatistic gr:newest){
			for(ShelfRecord off:offGoodsRecord){
				if(gr.getShop().getId()==off.getShop().getId()&&gr.getGoods().getId()==off.getGoods().getId()){
					gr.setStock(gr.getStock()-off.getQuantity());
				}
			}
			for(ShipmentRecord shipment:shipmentGoodsRecord){
				if(gr.getShop().getId()==shipment.getShop().getId()&&gr.getGoods().getId()==shipment.getGoods().getId()){
					gr.setStock(gr.getStock()-shipment.getQuantity());
				}
			}
		}

		for(GoodsStatistic gr:newest){

			GoodsStatistic goodsRecord=dao.selectGoodsStatisticByShopAndGoods(gr.getShop(),gr.getGoods());
			if(goodsRecord!=null){
				int stock=goodsRecord.getStock();
				if(stock!=gr.getStock()){
					goodsRecord.setStock(gr.getStock());
					boolean isSuccess=dao.updateGoodsStatistic(goodsRecord);
					if(!isSuccess){
						OMSConsole.println("update failed.");
						break;
					}
				}
			}
			else{
				boolean isSuccess=dao.insertGoodsStatistic(gr);
				if(!isSuccess){
					OMSConsole.println("update failed.");
					break;
				}
			}
		}
		
	}
}
